<!--  创建订单  -->
<template>
  	<div class="page_rela_container">
		<div class="scroll_auto flex_cell">

    <el-form id="page_order_create" ref="form" :model="form" :rules="rules" class="common-form-panel-div "
      v-loading="loading" label-position="right" label-width="140px">
      <ex_header_spiler :title="$tt('label_customer_info')" v-if="!isCustomerSystem"></ex_header_spiler>
      <el-row v-if="!isCustomerSystem">
        <el-col>
          <el-form-item :label="$tt('label_customer', '客户')" prop="customerId" key="customerId">
            <common_customer_choose v-model="form.customerId"
              :currentLabel="form.customerId ? $formatNameCode(form.customerName, form.customerCode) : null"
              @changeItem="changeCustomer" :disabled="edit" style="width: 100%;"></common_customer_choose>
          </el-form-item>
        </el-col>
      </el-row>
      <ex_header_spiler :title="$tt('label_inbound_info')"></ex_header_spiler>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_destination_warehouse', '目的仓库')" prop="destinationWarehouseId">
            <ex_super_input :value="form.destinationWarehouseId" class="w_fill" :items="EndWarehouseList" :attrs="{
              option: (e) => ({ label: $formatNameCode(e.warehouseName || e.name, e.warehouseCode || e.code), value: e['warehouseId'] || e.id }),
            }" type="select" @changeItem="endWarehouseChange" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_business_type', '业务类型')" prop="bizType" key="bizType">
            <ex_super_input :value="form.bizType" type="select" enum="BizTypeEnum" @change="changeBizType"
              class="w_fill" />
          </el-form-item>
        </el-col>
        <el-col v-show="!$loginUser.ifElse英威特">
          <el-form-item :label="$tt('label_inbound_type', '入库类型')" prop="inboundType">
            <ex_super_input :value="form.inboundType" type="select" enum="InboundTypeEnum" key="inboundType"
              @change="changeInboundType" :disabled="isWarehouseInto" class="w_fill"
              :listHandler="list => list.filter(it => it != 'ALLOT')" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="!$loginUser.ifElse英威特">
        <el-col>
          <el-form-item :label="$tt('label_platform_reference_no', '平台参考编号')" prop="platformOrderNo">
            <ex_super_input v-model="form.platformOrderNo" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_expected_box_number',)" prop="expectBoxQty"
            :rules="isSkuDetailManage ? null : requiredNumberRule">
            <ex_super_input v-model="form.expectBoxQty" :disabled="isSkuDetailManage"
              @input="e => $set(form, 'expectSkuQty', e)" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_expected_sku_number',)" prop="expectSkuQty"
            :rules="isSkuDetailManage ? null : requiredNumberRule">
            <ex_super_input v-model="form.expectSkuQty" :disabled="true" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <el-form-item :label="$tt('label_expected_total_weight',)" prop="totalWeight"
            :rules="isSkuDetailManage ? null : requiredWeightRule">
            <ex_super_input v-model="form.totalWeight" :disabled="isSkuDetailManage" append="kg" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_expected_total_volume',)" prop="totalVolume"
            :rules="isSkuDetailManage ? null : requiredVolumeRule">
            <ex_super_input v-model="form.totalVolume" :disabled="isSkuDetailManage" append="m³" />
          </el-form-item>
        </el-col>
      </el-row>
      <ex_header_spiler :title="$tt('label_transport_info')"></ex_header_spiler>
      <el-row>
        <el-col v-if="inboundTypeTRANSIT">
          <el-form-item :label="$tt('label_transit_warehouse', '中转仓库')" prop="transitWarehouseId">
            <ex_super_input :value="form.transitWarehouseId" class="w_fill" :items="StartWarehouseList" :attrs="{
              option: (e) => ({ label: $formatNameCode(e.warehouseName || e.name, e.warehouseCode || e.code), value: e['warehouseId'] || e.id }),
            }" type="select" @changeItem="startWarehouseChange" />
          </el-form-item>
        </el-col>
        <el-col v-if="inboundTypeTRANSIT">
          <el-form-item :label="$tt('label_logistics', '物流产品')" prop="productId">
            <ex_super_input :value="form.productId" class="w_fill" no-data-text="请先选择目的仓库" :items="ProductList" :attrs="{
              option: (e) => ({ label: $formatNameCode(e.productName, e.productCode), value: e['productId'] }),
            }" type="select" @changeItem="productChange" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="inboundTypeTRANSIT">
        <el-col>
          <el-form-item :label="$tt('label_delivery_type', '交货方式')" prop="deliveryType">
            <ex_super_input v-model="form.deliveryType" type="select" enum="DeliveryTypeEnum" key="deliveryType"
              class="w_fill" />
          </el-form-item>
        </el-col>
        <el-col v-if="deliveryTypeDELIVERY">
          <el-form-item :label="$tt('label_self_delivery_method', '自送方式')" prop="deliveryMode">
            <ex_super_input v-model="form.deliveryMode" type="select" enum="DeliveryModeEnum" key="deliveryMode"
              class="w_fill" />
          </el-form-item>
        </el-col>
      </el-row>

      <div v-show="inboundTypeTRANSIT">
        <div v-show="deliveryModeSelfDelivery">
          <el-row>
            <el-col>
              <el-form-item :label="$tt('label_self_delivery_driver_name', '联系人')" prop="driverName">
                <ex_super_input v-model="form.driverName" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="$tt('label_self_delivery_driver_phone', '联系方式')" prop="driverPhone">
                <ex_super_input v-model="form.driverPhone" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item :label="$tt('label_self_delivery_car_code', '车牌号')" prop="vehicleNo">
                <ex_super_input v-model="form.vehicleNo" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="$tt('label_expected_arrival_date', '预计到达时间')" prop="expectedDate">
                <ex_super_input v-model="form.expectedDate" type="date-picker" key="expectedDate"
                  :disabled="isWarehouseInto" :attrs="{ type: 'datetime', pickerOptions: { shortcuts: 'defaultAfter' } }"
                  style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div v-show="deliveryModeLogistics">

          <el-row>
            <el-col>
              <el-form-item :label="$tt('label_logistics_company', '物流公司')" prop="deliveryCompany">
                <ex_super_input v-model="form.deliveryCompany" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="$tt('label_logistics_track_code', '物流单号')" prop="deliveryTrackingNumber">
                <ex_super_input v-model="form.deliveryTrackingNumber" />
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col>
              <el-form-item :label="$tt('label_logistics_sender', '发件人')" prop="deliverySender">
                <ex_super_input v-model="form.deliverySender" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="$tt('label_expected_arrival_date', '预计到达时间')" prop="expectedDate">
                <ex_super_input v-model="form.expectedDate" type="date-picker" key="expectedDate"
                  :disabled="isWarehouseInto" :attrs="{ type: 'datetime', }" style="width:100%" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="2">
              <el-form-item :label="$tt('label_logistics_send_address', '发件地址')" prop="deliveryAddress">
                <ex_super_input v-model="form.deliveryAddress" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div v-show="deliveryTypeCOLLECT">
          <el-row>
            <el-col>
              <el-form-item :label="$t('label_quick_select_address')">
                <quick_select_customer_address :customerId="form.customerId" @command="item => {
                  form.omsInboundReceivingAddressDTO.contacter = item.contacts
                  form.omsInboundReceivingAddressDTO.contactPhone = item.contactNumber
                  form.omsInboundReceivingAddressDTO.county = item.county
                  form.omsInboundReceivingAddressDTO.province = item.province
                  form.omsInboundReceivingAddressDTO.city = item.city

                  form.omsInboundReceivingAddressDTO.street = item.addressDetail
                }" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item :label="$tt('label_collect_person', '联系人')" prop="omsInboundReceivingAddressDTO.contacter">
                <ex_super_input v-model="form.omsInboundReceivingAddressDTO.contacter"
                  key="omsInboundReceivingAddressDTO.contacter" />
              </el-form-item>
            </el-col>
            <el-col>
              <el-form-item :label="$tt('label_collect_contact', '联系方式')"
                prop="omsInboundReceivingAddressDTO.contactPhone">
                <ex_super_input v-model="form.omsInboundReceivingAddressDTO.contactPhone"
                  key="omsInboundReceivingAddressDTO.contactPhone" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col>
              <el-form-item :label="$tt('label_collect_region', '揽收地区')" prop="omsInboundReceivingAddressDTO.county">

                <china_address_select class="w_fill" :province.sync="form.omsInboundReceivingAddressDTO.province"
                  :city.sync="form.omsInboundReceivingAddressDTO.city"
                  :county.sync="form.omsInboundReceivingAddressDTO.county" />

              </el-form-item>
            </el-col>

            <el-col>
              <el-form-item :label="$tt('label_collect_address', '揽收地址')" prop="omsInboundReceivingAddressDTO.street">
                <ex_super_input v-model="form.omsInboundReceivingAddressDTO.street"
                  key="omsInboundReceivingAddressDTO.street" />
              </el-form-item>
            </el-col>
          </el-row>

        </div>


      </div>
      <el-row v-show="!inboundTypeTRANSIT">
        <el-col>
          <el-form-item :label="$tt('label_track_code', '跟踪号')" prop="mainTrackingNumber">
            <ex_super_input v-model="form.mainTrackingNumber" key="mainTrackingNumber" />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_expected_arrival_date', '预计到达时间')" prop="expectedDate">
            <ex_super_input v-model="form.expectedDate" type="date-picker" key="expectedDate" :disabled="isWarehouseInto"
              :attrs="{ type: 'datetime', pickerOptions: { shortcuts: 'defaultAfter' } }" style="width:100%" />
          </el-form-item>
        </el-col>
      </el-row>
      <ex_header_spiler :title="$tt('label_value_add_service')" v-show="!$loginUser.ifElse英威特 && !hiddenValueAddService">
      </ex_header_spiler>
      <el-row v-show="!$loginUser.ifElse英威特 & !hiddenValueAddService">
        <el-col>
          <el-form-item prop="customsService">
            <template v-slot:label>{{ $tt('label_customs_service', '报关服务') }}<i class="el-icon-question"></i></template>
            <ex_super_input v-model="form.customsService" type="radio-group" key="customsService" class="w_fill"
              :disabled="true" :attrs="{
                i18n: true,
                items: [{ _label: 'label_agent_customs', _value: 'Y' }, { _label: 'label_self_customs', _value: 'N' }]
              }" />
          </el-form-item>
        </el-col>

        <el-col>
          <el-form-item prop="customsType">
            <template v-slot:label>{{ $tt('label_customs_type', '报关类型') }}<i class="el-icon-question"></i></template>
            <div class="w_fill">
              <ex_super_input v-model="form.customsType" type="select" key="customsType" enum="CustomsTypeEnum"
                class="w_fill" style="width: 260px;" />
              <div class="color_danger" v-if="form.customsType == 'SEPARATE_TAX' && form.customsService == 'Y'">
                {{ $tt('label_refund_customs_declaration_fee') }}：1000RMB/票
              </div>
            </div>
          </el-form-item>
        </el-col>
        <el-col style="width: 200px;">
          <el-form-item label-width="0">
            <el-checkbox style="margin-left: 40px;" v-model="form.isWarehouseReceiptPrevail" true-label="Y"
              false-label="N">{{ $tt('label_subject_to_quantity_received_in_warehouse') }} <i
                class="el-icon-question"></i></el-checkbox>
          </el-form-item>
        </el-col>

      </el-row>


      <el-row v-show="!$loginUser.ifElse英威特 & !hiddenValueAddService">
        <el-col>
          <el-form-item :label="$tt('label_is_insurance', '是否投保')" prop="isInsurance">
            <ex_radio_group_auto :value="form.isInsurance" key="isInsurance" class="w_fill" :disabled="!CanInsurance"
              @input="changeInsurance" enum='YesOrNoEnum' />
          </el-form-item>
        </el-col>
        <el-col>
          <el-form-item :label="$tt('label_sum_insurance_amount', '统计投保金额')" prop="insuranceValue"
            v-if="form.isInsurance == 'Y'">
            {{ insuredAmountSum }} {{ currencyList.length == 0 ? '' : currencyList.length >= 2 ?
              this.$tt("label_mult_insured_curreny") :
              `[${currencyList.join(',')}]` }}
          </el-form-item>
        </el-col>
      </el-row>

      <ex_header_spiler :title="$tt('label_sku_specification', '商品信息')"></ex_header_spiler>
      <el-row>
        <template v-if="TOB">
          <el-col v-if="inboundTypeTRANSIT">
            <el-form-item :label="$tt('label_require_sku_detail_manage')" prop="boxDetailIsEmpty">
              <ex_super_input :value="form.boxDetailIsEmpty" type="radio-group" key="boxDetailIsEmpty" class="w_fill"
                @input="changeBoxDetailManage" :attrs="{
                  enum: 'YesOrNoOppositeEnum'
                }" />
            </el-form-item>
          </el-col>
          <el-col v-if="isSkuDetailManage && false">
            <el-form-item :label="$tt('label_has_pallet', '是否已打托')" prop="isCustomerPallet">
              <ex_super_input :value="form.isCustomerPallet" type="radio-group" key="isCustomerPallet" class="w_fill"
                @input="changeCustomerPallet" :attrs="{
                  enum: 'YesOrNoEnum'
                }" />
            </el-form-item>
          </el-col>
        </template>
        <el-col v-if="isSkuDetailManage && $loginUser.ifElse澳越">
          <el-form-item :label="$tt('label_is_box_code_manage', '是否箱号管理')" prop="boxIsEmpty">
            <ex_super_input :value="form.boxIsEmpty" type="radio-group" key="boxIsEmpty" class="w_fill"
              @input="changeBoxIsEmpty" :attrs="{
                enum: 'YesOrNoOppositeEnum'
              }" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="isSkuDetailManage">
        <el-col :span="3">
          <el-form-item>
            <el-button icon="el-icon-plus" @click="clickSkuBoxAdd" type="primary" v-if="BoxCodeManage">
              <!--  新增箱-->
              {{ $tt('label_add_box',) }}
            </el-button>
            <el-button icon="el-icon-plus" @click="clickSkuAdd" type="primary" v-if="!BoxCodeManage">
              {{ $tt('label_add_sku',) }}
            </el-button>
            <el-button @click="printSkuBarcode(form.omsBoxSkuInfoVOList)">
              <!-- 打印商品条码 -->
              {{ $tt('label_print_sku_barcode',) }}
            </el-button>
            <el-button @click="printBoxNo(groupBoxList)" v-if="BoxCodeManage">
              <!--  打印箱标签-->
              {{ $tt('label_print_box_tag',) }}
            </el-button>
            <el-button v-if="IsHasPALLET">
              <!-- 打印托标签-->
              {{ $tt('label_print_pallet_tag',) }}
            </el-button>
            <el-upload class="mg_l2" action="" :show-file-list="false" style="display: inline;"
              :http-request="uploadSkuFile">
              <el-button slot="trigger" size="mini" type="primary">{{ $tt('label_sku_import') }}</el-button>
            </el-upload>
            <select_file_temp class="mg_l2" service="OMS" module="INBOUND_SKU_DETAIL"
              :label="$tt('label_sku_import_template')" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="isSkuDetailManage">
        <el-col style="width: 100%;">
          <el-form-item class="w_fill" prop="omsBoxSkuInfoVOList"
            :label="$tt(BoxCodeManage ? 'label_box_specification' : 'label_sku_specification')">
            <template v-if="BoxCodeManage">
              <el-tabs type="border-card" class="tabs_no_horizontal_pad">
                <el-tab-pane :label="$t('label_box_list')">
                  <ex_super_table v-bind="boxTableOption" :data="groupBoxList" ref="TableSku" style="min-height:300px">
                    <template v-slot:expand="{ row }">
                      <ex_super_table v-bind="skuItemTableOption" :data="row.items">
                      </ex_super_table>
                    </template>
                  </ex_super_table>
                </el-tab-pane>
                <el-tab-pane :label="$t('label_sku_list')">
                  <ex_super_table v-bind="skuTableOption" :data="form.omsBoxSkuInfoVOList" style="min-height:300px">
                  </ex_super_table>
                </el-tab-pane>
              </el-tabs>
            </template>

            <ex_super_table v-bind="skuItemTableOption" :data="form.omsBoxSkuInfoVOList" v-else style="min-height:300px">
            </ex_super_table>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="3">
          <el-form-item class="w_fill " prop="attachedDTOList" :required="RequiredAttached">
            <template v-slot:label>
              {{ $tt('label_attachment_info') }}
              <select_file_temp service="OMS" module="INBOUND_ATTACHMENT" :label="$tt('label_attached_template')" />
            </template>
            <!--            <div style="background-color: rgba(0, 0, 0, 0.02);padding: 10px;margin-bottom: 10px;" class="color_info">-->
            <!--              若有补充的文件，则可在此处上传。-->
            <!--            </div>-->
            <!-- <ex-upload-file ref="fileUpload" :value="form.attachedDTOList" type="upload-file" multiple :limit="5" drag
              accept='.xls,.xlsx,.doc,.docx' @input="fileUploadChange">
              <i class="el-icon-upload"></i>
              <div class="el-upload__text" v-html="$tt('tip_upload_attachment_drag_click')"></div>
            </ex-upload-file> -->

            <ex_super_upload ref="fileUpload" :value="form.attachedDTOList" :isUpload.sync="form.isUpload" type="file"
              :limitTip="true" multiple :limit="5" drag accept='.xls,.xlsx,.doc,.docx' @input="fileUploadChange">
              <template v-slot:trigger>
                <i class="el-icon-upload"></i>
                <div class="el-upload__text" v-html="$tt('tip_upload_attachment_drag_click')"></div>
              </template>
            </ex_super_upload>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <ex_header_spiler :title="$tt('备注', '其他信息')"></ex_header_spiler> -->
      <el-row>
        <el-col :span="2">
          <el-form-item prop="description" :label="$tt('label_remark')">
            <el-input type="textarea" v-model="form.description"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <!-- ============================NEW================================= -->

    </el-form>


    <add_box ref="add_box" @submitSuccess="boxAddSuccess" />
    <add_sku ref="add_sku" @submitSuccess="skuAddSuccess" />
  </div>
    <div class="page_rela_bottom_area">
      <template v-if="onlySave">
        <el-button type="primary" @click="submit('SAVE_AUDIT')">{{ $tt('label_submit_and_audit') }}</el-button>
      </template>
      <template v-else>
        <el-button @click="submit('SAVE')">{{ $tt('label_save_to_draft') }}</el-button>
        <el-button type="primary" @click="submit('SAVE_AUDIT')">{{ $tt('label_submit_and_audit') }}</el-button>
      </template>
      <el-button @click="return_page_back">{{ $tt('label_cancel') }}</el-button>
    </div>

    <print_sku ref="print_sku" itemKey="skuId" />
    <print_box ref="print_box" :basePrint="true" />
  </div>
</template>
<script>

let _default_form = {
  customerId: "",
  destinationWarehouseId: "",
  destinationWarehouseCode: "",
  destinationWarehouseName: "",
  transitWarehouseId: "",
  transitWarehouseCode: "",
  transitWarehouseName: "",
  productId: "",
  productName: "",
  productCode: "",
  status: 'DRAFT',
  inboundType: "TRANSIT",
  deliveryType: "DELIVERY",
  deliveryMode: "",

  bizType: 'TOC',
  needCustomerAudit: "N",
  expectBoxQty: "",
  expectSkuQty: "",
  totalWeight: "",
  totalVolume: "",

  isPallet: "N",//YesOrNoEnum 	是否打托: Y 是, N 否
  isCustomerPallet: "N",//

  isWarehouseEdit: 'N',

  inboundReason: "",
  isInsurance: "N",
  insuranceValue: "0",
  customsService: "Y",
  customsType: "",
  expectedDate: "",

  vehicleNo: "",//自送车牌号
  driverName: "",//司机名称
  driverPhone: "",

  deliveryCompany: "",
  deliveryTrackingNumber: "",
  deliverySender: "",
  deliveryAddress: "",

  platformOrderNo: "",//平台参考编号


  description: "",
  mainTrackingNumber: "",//跟踪号
  attachedDTOList: [],//附件相关内容

  omsBoxSkuInfoVOList: [],//sku相关内容传参
  isWarehouseReceiptPrevail: 'Y',
  boxDetailIsEmpty: 'N',
  boxIsEmpty: 'N',
  omsInboundReceivingAddressDTO: {
    province: "",
    city: "",
    county: "",
    street: "",
    contacter: "",
    contactPhone: "",
  }
}
import router_params from '@/mixin/router_params';
import add_box from './dialog/add_box.vue';
import add_sku from './dialog/add_sku.vue';

import cascader_address_select from '@/component/tms/cascader_address_select'
import print_sku from '@/component/print/print_sku'
import print_box from '@/component/print/print_box'
import role_system_mixin from '@/mixin/role_system_mixin';

import select_file_temp from '@/component/base/select_file_temp'
import quick_select_customer_address from '@/component/oms/quick_select_customer_address'



export default {
  title: 'inbound_order_operate',
  components: {
    add_box, add_sku, cascader_address_select, print_sku, print_box, select_file_temp,
    quick_select_customer_address
  },
  mixins: [router_params, role_system_mixin],

  data() {
    return {
      edit: false,
      wms: false,
      loading: false,


      hiddenValueAddService: false,

      //维护仓库到产品
      products: [],
      requiredNumberRule: [
        { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        {
          trigger: 'blur',
          validator: (r, v, cb) => {
            if (!this.$reg.PureNumber(v)) {
              return cb(this.$tt("tip_only_positive_pure_decimal"))
            } else if (Number(v <= 0)) {
              return cb(this.$tt("tip_no_less_equal_any", { type: "0" }))
            }
            cb()
          }
        },
      ],
      requiredWeightRule: { required: true, label: 'label_expected_total_weight', trigger: 'blur', validator: (r, v, cb) => this.$ruleStandard({ v, cb, type: 'weight', required: true, }) ? cb() : null, },
      requiredVolumeRule: { required: true, label: 'label_expected_total_volume', trigger: 'blur', validator: (r, v, cb) => this.$ruleStandard({ v, cb, type: 'volume', required: true, }) ? cb() : null, },
      rules: {
        bizType: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        boxIsEmpty: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

        boxDetailIsEmpty: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        inboundReason: [{
          required: true, validator: (r, v, cb) => {
            this.isWarehouseInto && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],
        customerId: [{
          required: true, validator: (r, v, cb) => {
            _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],
        inboundType: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
        destinationWarehouseId: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
        // platformOrderNo: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],

        transitWarehouseId: [{
          required: true, validator: (r, v, cb) => {
            this.inboundTypeTRANSIT && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],
        deliveryType: [{
          required: true, validator: (r, v, cb) => {
            this.inboundTypeTRANSIT && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],
        deliveryMode: {
          required: true, validator: (r, v, cb) => {
            this.deliveryTypeDELIVERY && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        },
        productId: [{
          required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur'
        }],


        'omsInboundReceivingAddressDTO.county': [{
          required: true, validator: (r, v, cb) => {
            this.deliveryTypeCOLLECT && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],

        'omsInboundReceivingAddressDTO.street': [{
          required: true, validator: (r, v, cb) => {
            this.deliveryTypeCOLLECT && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],
        'omsInboundReceivingAddressDTO.contacter': [{
          required: true, validator: (r, v, cb) => {
            this.deliveryTypeCOLLECT && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        }],
        'omsInboundReceivingAddressDTO.contactPhone': {
          required: true, validator: (r, v, cb) => {
            this.deliveryTypeCOLLECT && _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        },

        customsType: {
          required: true, validator: (r, v, cb) => {
            _.isEmpty(v) ? cb(this.$tt('tip_can_no_empty')) : cb()
          }, trigger: 'blur'
        },
        customsService: [{ required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' }],
        attachedDTOList: [{
          type: 'array', validator: (r, v, cb) => {
            if (this.form.isUpload) {
              cb(this.$t("label_uploading"))
            } else if (this.RequiredAttached && v.length == 0) {
              cb(this.$t('tip_please_upload_least_one_file'))
            } else {
              cb()
            }
          }, trigger: 'blur'
        }],

        isWarehouseReceiptPrevail: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        isInsurance: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },
        isCustomerPallet: { required: true, message: this.$tt('tip_can_no_empty'), trigger: 'blur' },

        omsBoxSkuInfoVOList: [
          {
            required: true, trigger: 'blur', type: "array", min: 1,
            message: this.$tt('tip_please_add_least_one_sku'),
          },
          {
            trigger: 'blur', type: "array",
            validator: (r, v, cb) => {
              if (this.BoxCodeManage) {
                if (v.some(it => !it.boxNo)) {
                  return cb(this.$tt("tip_type_can_no_empty", { type: "label_box_code", i18n: true }))
                } else if (v.some(it => !it.boxWeight || !it.boxLength || !it.boxWidth || !it.boxHeight)) {
                  return cb(this.$tt("tip_box_weight_size_can_no_empty"))
                }
              }
              cb()
            }
          },
          {
            trigger: 'blur', type: "array",
            validator: (r, v, cb) => {
              const skuGroup = _.groupBy(v, it => `${it.boxNo}=${it.skuId}`)
              if (_.values(skuGroup).some(it => it.length > 1)) {
                return cb(this.$tt("tip_some_box_can_no_have_some_sku"))
              }
              cb()
            }
          },
          {
            trigger: 'blur', type: "array",
            validator: (r, v, cb) => {
              if (this.IsHasPALLET && v.some(it => _.isEmpty(it.palletNo))) {
                return cb(this.$tt(["label_pallet_code", "tip_can_no_empty"]))
              }
              cb()
            }
          },

        ],
      },
      form: this.getDefaultForm(),

      skuTableOption: {
        model: [
          {
            key: 'boxNo', label: 'label_box_code', 'min-width': 150,
          },
          { key: 'skuName', label: 'label_sku_name', 'min-width': 120, 'show-overflow-tooltip': true, },
          { key: 'skuBarcode', label: 'label_sku_code', 'show-overflow-tooltip': true, },
          {
            key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': '150',
          },
          {
            key: 'isElectrify', label: 'label_is_electrify', width: '120', 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum")
          },

          {
            key: 'cartonSpec', label: 'label_carton_spec', if: () => this.TOB,
            formatter: (r, c, v) => v ? `${v}/${this.$tt('label_box')}` : this.$t('data_temp_none'),
          },
          {
            key: 'quantity', label: 'label_inbound_count', 'min-width': 120,
          },
          {
            key: 'skuDeclaredAmount', label: 'label_declared_value', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
          },
          {
            key: 'insuredAmount', label: 'label_insurance_amount', 'min-width': 120, if: () => !this.$loginUser.ifElse英威特,
            formatter: (r, c, v) => r.isInsurance == 'N' ? this.$tt('data_none') : this.$formatNameCode(v, r.currencyCode),
          },
        ],
      },
      skuItemTableOption: {
        model: [
          { key: 'skuName', label: 'label_sku_name', 'min-width': 120, 'show-overflow-tooltip': true, },
          { key: 'skuBarcode', label: 'label_sku_code', 'show-overflow-tooltip': true, },
          {
            key: 'skuOnlyCode', label: 'label_sku_only_code', 'min-width': '150',
          },
          {
            key: 'isElectrify', label: 'label_is_electrify', width: '120', 'show-overflow-tooltip': true,
            formatter: (r, c, v, i) => this.$enumShow(v, "YesOrNoEnum")
          },

          {
            key: 'cartonSpec', label: 'label_carton_spec', if: () => this.TOB,
            formatter: (r, c, v) => v ? `${v}/${this.$tt('label_box')}` : this.$t('data_temp_none'),
          },
          {
            key: 'quantity', label: 'label_inbound_count', 'min-width': 120,
          },
          {
            key: 'skuDeclaredAmount', label: 'label_declared_value', 'width': 120, 'show-overflow-tooltip': true,
            formatter: (r, c, v) => this.$formatNameCode(v, r.currencyCode),
          },
          {
            key: 'insuredAmount', label: 'label_insurance_amount', 'min-width': 120, if: () => !this.$loginUser.ifElse英威特,
            formatter: (r, c, v) => r.isInsurance == 'N' ? this.$tt('data_none') : this.$formatNameCode(v, r.currencyCode),
          },
          {
            type: 'operate', width: 130, if: () => !this.BoxCodeManage, operate: [
              {
                label: "label_remove", class: "button_text_danger",
                click: (row, i, list) => {
                  list.splice(i, 1)
                  this.refreshOrderSkuChange()
                }
              },
            ]
          }
        ]
      },
      boxTableOption: {
        model: [
          { type: 'selection', clickToggle: true, },
          { type: 'expand', slot: "expand" },
          {
            key: 'palletNo', label: 'label_pallet_code', if: () => this.IsHasPALLET,
            'min-width': '150',
          },
          {
            key: 'boxNo', label: 'label_box_code', 'min-width': '150',
          },

          {
            key: 'skuKind', label: 'label_sku_kind',
            'width': 100, 'show-overflow-tooltip': true,
          },
          {
            key: 'skuSum', label: 'label_sku_count_sum',
            'width': 100, 'show-overflow-tooltip': true,
          },


          { key: 'boxWeight', label: 'label_box_weight', 'width': 100, formatter: (r, c, v) => this.$addUnit(this.$formatDigit(v), 'kg') },

          { key: 'boxLength', label: 'label_box_length', 'width': 100, formatter: (r, c, v) => this.$addUnit(this.$formatDigit(v, 2), 'cm') },
          { key: 'boxWidth', label: 'label_box_width', 'width': 100, formatter: (r, c, v) => this.$addUnit(this.$formatDigit(v, 2), 'cm') },
          { key: 'boxHeight', label: 'label_box_height', 'width': 100, formatter: (r, c, v) => this.$addUnit(this.$formatDigit(v, 2), 'cm') },

          {
            key: 'insuredAmount', label: 'label_sum_insurance_amount', 'width': 120, if: () => !this.$loginUser.ifElse英威特,
            formatter: (r, c, v) => r.isInsurance == 'N' ? this.$tt('data_none') : this.$formatNameCode(v, r.currencyCode),
          },
          {
            type: 'operate', width: 170, operate: [
              {
                label: "label_edit",
                click: (row) => this.clickSkuBoxEdit(row)
              },
              {
                label: "label_sku_list",
                click: (row) => {
                  this.$refs.TableSku.toggleRowExpansion(row)
                }
              },
              {
                label: "label_remove", class: "button_text_danger",
                click: (row, i) => this.removeBox(row)
              },
            ]
          }
        ],
      },
    };
  },
  computed: {
    RequiredAttached() {
      return !this.$loginUser.ifElse澳越//this.inboundTypeTRANSIT //&& this.form.customsType == 'SEPARATE_TAX'
    },
    //使用计算属性获取仓库
    StartWarehouseList() {
      let list = this.products
      if (this.inboundTypeTRANSIT) {
        list = list.filter(it => it.endWarehouse && it.endWarehouse.some(w => w.warehouseId == this.form.destinationWarehouseId))
      }
      list = list.filter(it => it.startWarehouse).map(it => it.startWarehouse)
      return _.unionBy(_.concat(...list), it => it.warehouseId)
    },
    EndWarehouseList() {
      if (this.inboundTypeTRANSIT) {
        let list = this.products
        // if (this.inboundTypeTRANSIT) {
        //   list = list.filter(it => it.startWarehouse && it.startWarehouse.some(w => w.warehouseId == this.form.transitWarehouseId))
        // }
        list = list.filter(it => it.endWarehouse).map(it => it.endWarehouse)
        return _.unionBy(_.concat(...list), it => it.warehouseId)
      } else {
        return this.$store.getters.destinationWarehouseList
      }

    },
    ProductList() {
      let list = this.products.filter(it =>
        it.endWarehouse && it.endWarehouse.some(w => w.warehouseId == this.form.destinationWarehouseId)
      )
      if (this.inboundTypeTRANSIT) {
        list = list.filter(it => it.startWarehouse && it.startWarehouse.some(w => w.warehouseId == this.form.transitWarehouseId))
      }
      return list
    },


    //判断当前产品是否支持保险
    ProductSupportInsurance() {
      const select_product = _.find(this.ProductList, it => it.productId == this.form.productId)
      if (select_product) {
        return !!select_product.supportInsurance
      }
      return false
    },



    CanInsurance() {
      return this.inboundTypeTRANSIT && this.ProductSupportInsurance
    },
    IsSelectInsurance() {
      return this.form.isInsurance == "Y"
    },
    IsHasPALLET() {
      return this.form.isPallet == "Y"
    },
    TOB() {
      return this.form.bizType == 'TOB'
    },
    onlySave() {
      return !['DRAFT', 'AUDIT_REJECT'].some(it => it == this.form.status)
    },
    //数据来源-手工录入属性
    isWarehouseInto() {
      return this.form.isWarehouseEdit == 'Y'
    },
    //入库类型-中转入库
    inboundTypeTRANSIT() {
      return this.form.inboundType == 'TRANSIT'
    },


    //交货方式-揽收
    deliveryTypeCOLLECT() {
      return this.inboundTypeTRANSIT && this.form.deliveryType == 'COLLECT'
    },
    deliveryTypeDELIVERY() {
      return this.inboundTypeTRANSIT && this.form.deliveryType == 'DELIVERY'
    },

    deliveryModeSelfDelivery() {
      return this.deliveryTypeDELIVERY && this.form.deliveryMode == 'DELIVERY'
    },
    deliveryModeLogistics() {
      return this.deliveryTypeDELIVERY && this.form.deliveryMode == 'LOGISTICS'
    },
    // isInsuranceY() {
    //   return this.inboundTypeTRANSIT && this.form.isInsurance == "Y"
    // },



    isSkuDetailManage() {
      return this.form.boxDetailIsEmpty != 'Y'
    },

    BoxCodeManage() {
      return this.form.boxIsEmpty != 'Y'
    },
    insuredAmountSum() {
      if (this.form.isInsurance == "Y") {
        let sum = 0;
        this.form.omsBoxSkuInfoVOList.map(it => sum = this.$math_add(sum,
          it.isInsurance == "Y" ? this.$math_mul(it.insuredAmount, it.quantity) : 0))
        return sum
      } else {
        return 0
      }
    },
    currencyList() {
      return _.uniqBy(this.form.omsBoxSkuInfoVOList, "currencyCode").map(it => it.currencyCode)
    },
    uniqBoxList() {
      return _.uniqBy(this.form.omsBoxSkuInfoVOList, "boxNo")
    },
    groupBoxList() {
      let g = _.groupBy(this.form.omsBoxSkuInfoVOList, 'boxNo')
      return _.values(g).filter(it => !_.isEmpty(it)).map(it => {
        let item = _.head(it)
        return {
          boxNo: item.boxNo,
          boxNumber: item.boxNumber,
          palletNo: item.palletNo,
          boxLength: item.boxLength,
          boxWidth: item.boxWidth,
          boxHeight: item.boxHeight,
          boxWeight: item.boxWeight,
          skuKind: it.length,
          skuSum: _.reduce(it, (r, v) => this.$math_add(r, (v.quantity)), 0),
          insuredAmount: _.reduce(it, (r, v) => this.$math_add(r, (v.insuredAmount)), 0),
          isInsurance: it.some(sku => sku.isInsurance == 'Y') ? 'Y' : 'N',
          currencyCode: _.uniqBy(it, "currencyCode").map(it => it.currencyCode).join(','),
          items: it,
        }
      })
    },
  },

  created() {
    this.initProduct()
  },


  methods: {
    changeInitDeliveryInfo(e) {
      if (this.inboundTypeTRANSIT) {
        if (this.deliveryTypeDELIVERY) {
          this.form.omsInboundReceivingAddressDTO.contacter = null
          this.form.omsInboundReceivingAddressDTO.contactPhone = null
          this.form.omsInboundReceivingAddressDTO.province = null
          this.form.omsInboundReceivingAddressDTO.city = null
          this.form.omsInboundReceivingAddressDTO.county = null
          this.form.omsInboundReceivingAddressDTO.street = null
          if (this.deliveryModeSelfDelivery) {
            this.form.deliveryCompany = null
            this.form.deliveryTrackingNumber = null
            this.form.deliverySender = null
            this.form.deliveryAddress = null
          } else if (this.deliveryModeLogistics) {
            this.form.driverName = null
            this.form.driverPhone = null
            this.form.vehicleNo = null
          }
        } else if (this.deliveryTypeCOLLECT) {

          this.$set(this.form, "deliveryMode", null)

          this.form.deliveryCompany = null
          this.form.deliveryTrackingNumber = null
          this.form.deliverySender = null
          this.form.deliveryAddress = null

          this.form.driverName = null
          this.form.driverPhone = null
          this.form.vehicleNo = null
          this.form.expectedDate = null
        }


      } else {
        this.$set(this.form, "deliveryType", null)
        this.$set(this.form, "deliveryMode", null)



        this.form.deliveryCompany = null
        this.form.deliveryTrackingNumber = null
        this.form.deliverySender = null
        this.form.deliveryAddress = null
        this.form.driverName = null
        this.form.driverPhone = null
        this.form.vehicleNo = null
        this.form.omsInboundReceivingAddressDTO.contacter = null
        this.form.omsInboundReceivingAddressDTO.contactPhone = null
        this.form.omsInboundReceivingAddressDTO.province = null
        this.form.omsInboundReceivingAddressDTO.city = null
        this.form.omsInboundReceivingAddressDTO.county = null
        this.form.omsInboundReceivingAddressDTO.street = null
      }
      if (this.form.productId) {
				const e = _.find(this.ProductList, (it) => it.productId == this.form.productId);
				if (e) {
					this.form.productName = e.productName;
					this.form.productCode = e.productCode;
				}
			}
    },
    printBoxNo(list) {
      if (_.isEmpty(list)) return this.$message.error(this.$tt('tip_please_add_least_one_box'))

      this.$refs.print_box.show(list.map(it => ({
        binNo: it.boxNo,
        orderNo: this.form.receivingOrderCode,
        binCount: this.uniqBoxList.length,
        targetWarehouse: this.form.destinationWarehouseName,
        customerCode: this.form.customerCode,
        skuCategoryNum: it.skuKind,
        skuCount: it.skuSum,
        binWeight: it.boxWeight,
        boxNumber: it.boxNumber,
        items:it.items,
        skuOnlyCodeNumMap: it.items.map(it => `${it.skuOnlyCode} * ${it.quantity}`).join(" , ")
      })))
    },
    printSkuBarcode(list) {
      if (_.isEmpty(list)) return this.$message.error(this.$tt('tip_please_add_least_one_sku'))
      this.$refs.print_sku.show(_.uniqBy(list, it => it.skuId))
    },
    clickSkuBoxEdit(row) {
      this.$refs.add_box.show(
        {
          items: _.cloneDeep(this.form.omsBoxSkuInfoVOList),
          boxNo: row.boxNo,
          customerId: this.form.customerId,
          TOB: this.TOB, isPallet: this.IsHasPALLET, isInsured: this.IsSelectInsurance, customerCode: this.form.customerCode
        }
      )
    },
    clickSkuBoxAdd() {
      if (!this.form.customerId && !this.isCustomerSystem) return this.$message.warning(this.$tt("tip_please_select_first_customer"))
      this.$refs.add_box.show({
        items: _.cloneDeep(this.form.omsBoxSkuInfoVOList),
        boxNo: null,
        customerId: this.form.customerId,
        TOB: this.TOB, isPallet: this.IsHasPALLET, isInsured: this.IsSelectInsurance, customerCode: this.form.customerCode
      })
    },
    clickSkuAdd() {
      if (!this.form.customerId && !this.isCustomerSystem) return this.$message.warning(this.$tt("tip_please_select_first_customer"))
      this.$refs.add_sku.show({
        items: _.cloneDeep(this.form.omsBoxSkuInfoVOList),
        customerId: this.form.customerId,
        TOB: this.TOB,
        isInsured: this.IsSelectInsurance,
        customerCode: this.form.customerCode
      })
    },
    removeBox(row) {
      this.form.omsBoxSkuInfoVOList = this.form.omsBoxSkuInfoVOList.filter(it => it.boxNo != row.boxNo)
      this.refreshOrderSkuChange()
    },
    boxAddSuccess(obj) {
      let i = _.findIndex(this.form.omsBoxSkuInfoVOList, it => it.boxNo == obj.oriCode)
      if (i < 0) {
        this.form.omsBoxSkuInfoVOList.push(...obj.list)
      } else {
        let last = this.form.omsBoxSkuInfoVOList.filter(it => it.boxNo != obj.oriCode)
        last.splice(i, 0, ...obj.list)
        this.form.omsBoxSkuInfoVOList = last
      }
      this.refreshOrderSkuChange()
    },
    skuAddSuccess(obj) {
      // const will_adds = obj.list
      // .filter(addItem => {
      //   const item = _.find(this.form.omsBoxSkuInfoVOList, it => it.skuId == addItem.skuId)
      //   if (item) {
      //     item.quantity = this.$math_add(item.quantity, addItem.quantity)
      //     return false
      //   }
      //   return true
      // })
      this.form.omsBoxSkuInfoVOList = obj.list
      this.refreshOrderSkuChange()
    },
    changeBizType(e) {
      if (_.isEmpty(this.form.omsBoxSkuInfoVOList) || e == 'TOC') {
        this.form.bizType = e
        this.changeCustomerPallet("N")
        this.changeBoxDetailManage("N")
      } else {
        this.$confirm(this.$tt('tip_inbound_tob_change_will_happen'), this.$tt('label_tip'), {
          type: 'danger'
        }).then(() => {
          this.removeSkuAll()

          this.form.bizType = e
          // this.form.omsBoxSkuInfoVOList = _.unionBy(this.form.omsBoxSkuInfoVOList, 'boxNo')


          // this.form.omsBoxSkuInfoVOList.filter(sku => {
          //   return this.form.omsBoxSkuInfoVOList.filter(it => it.boxNo == sku.boxNo).length <= 1
          // })
        }).catch(() => {
        });
      }
    },


    getDefaultForm() {
      const moreDefault = {}
      if (this.$loginUser.ifElse英威特) {
        moreDefault.inboundType = "DIRECT"
      }
      return _.cloneDeep(Object.assign({}, _default_form, moreDefault,))
    },

    init_data_default(into_params) {
      this.form = this.getDefaultForm()
      if (this.isCustomerSystem) {
        this.form.customerId = this.$loginUser.userId
        this.form.customerName = this.$loginUser.userName
        this.form.customerCode = this.$loginUser.userCode
      }
      this.wms = !!into_params.wms
      if (this.wms) {
        this.form.isWarehouseEdit = 'Y'
        this.form.inboundReason = 'B2B_WAREHOUSE'
        this.form.inboundType = 'DIRECT'
        this.form.expectedDate = new Date().getTime()
      }
      let { copy, emitKey, title,oriBox, ...params } = into_params
      this.edit = !!into_params.edit
      if (this.edit || copy) {
        this.$ajax({
          url: this.$url['oms/inboundOrderDetailId'],
          method: 'post',
          loading: { text: this.$tt('tip_searching'), target: "#page_order_create" },
          data: params,
          success: (res) => {
            if (res.data) {
              if (!_.isEmpty(res.data.omsInboundReceivingSkuDTOList)) {
                res.data.omsBoxSkuInfoVOList = res.data.omsInboundReceivingSkuDTOList
              }
              if (copy) {
                this.copyHandle(res.data, oriBox)
              } else {
                this.form = Object.assign({}, this.form, res.data)
                this.refreshOrderSkuChange()
                if (!this.isSkuDetailManage) {
                  this.form.expectBoxQty = res.data.expectBoxQty
                  this.form.expectSkuQty = res.data.expectSkuQty
                  this.form.totalWeight = res.data.totalWeight
                  this.form.totalVolume = res.data.totalVolume
                }
              }
              this.refreshEndWarehouseLink()
            }
            this.fixTabLabel()
          }
        })
      } else {
      }

      this.fixTabLabel()
    },
    fixTabLabel() {
      if (this.edit && !!this.form.id) {
        this.$emit("tagModifyLabel", {
          _key: 'label_name_code', name: this.$tt(this.wms ? "label_edit_inbound_oder_form_wms" : "label_edit_inbound_oder"),
          code: this.form.receivingOrderCode || ""
        })
      } else {
        this.$emit('tagModifyLabel', this.wms ? "title_new_inbound_oder_form_wms" : "title_new_inbound_oder",)
      }
    },
    copyHandle(data,oriBox) {
      delete data.id
      delete data.gmtCreate
      delete data.gmtModify
      delete data.creator
      delete data.modifier
      data.status = 'DRAFT'
      if (data.appId) {
        delete data.platformOrderNo
      }
      // delete res.data.omsInboundReceivingAddressDTO
      data.omsBoxSkuInfoVOList.forEach(it => {
        delete it.id
        delete it.receivingId
        delete it.receivingCode
      })
      data.attachedDTOList.forEach(it => {
        delete it.id
        delete it.receivingId
        delete it.receivingCode
      })
      if (data.omsInboundReceivingAddressDTO) {
        delete data.omsInboundReceivingAddressDTO.id
        delete data.omsInboundReceivingAddressDTO.receivingId
        delete data.omsInboundReceivingAddressDTO.receivingCode
      }
      if (data.boxDetailIsEmpty == 'Y') {
        data.omsBoxSkuInfoVOList = []
        this.form = Object.assign({}, this.form, data)
        this.refreshOrderSkuChange()

      } else if (data.boxIsEmpty == 'Y') {
        data.omsBoxSkuInfoVOList = data.omsInboundReceivingSkuDTOList
        data.omsInboundReceivingSkuDTOList = []
        this.form = Object.assign({}, this.form, data)
        this.refreshOrderSkuChange()

      } else{
        const boxGroup = _.groupBy(data.omsBoxSkuInfoVOList, "boxNo")
        this.$ajax({
          url: this.$url['oms/generateBatchBoxNo'],
          method: 'post',
          loading: this.$tt("tip_rebuild_boxno_doing"),
          data: {
            customerCode: data.customerCode,
            number: _.keys(boxGroup).length
          },
          fail: () => {
            data.omsBoxSkuInfoVOList.forEach(it => it.boxNo = "")
            this.form = Object.assign({}, this.form, data)
            this.refreshOrderSkuChange()

            this.$alert(this.$tt('tip_rebuild_boxno_fail'), this.$tt('label_tip'), {});
          },
          success: (res) => {
            if (res && res.data && res.data.rows && res.data.rows.length == _.keys(boxGroup).length) {
              let boxIndex = 0
              _.forOwn(boxGroup, (v, k) => {
                v.forEach((sku, i) => {
                  sku.boxNo = res.data.rows[boxIndex]
                })
                boxIndex++
              })
            } else {
              data.omsBoxSkuInfoVOList.forEach(it => it.boxNo = "")
              this.$alert(this.$tt('tip_rebuild_boxno_fail'), this.$tt('label_tip'), {});
            }
            this.form = Object.assign({}, this.form, data)
            this.refreshOrderSkuChange()
          },
          complete: () => {
          }
        })
      }


    },
    fileUploadChange(flies) {
      flies.map((item, index) => {
        item.sort = index
      })
      this.form.attachedDTOList = [...flies]
    },
    changeBoxDetailManage(e) {
      if (e == "Y") {
        this.confirmClearBox(() => {
          this.form.boxDetailIsEmpty = e
          this.changeCustomerPallet("N")
          this.changeBoxIsEmpty("N")
          this.refreshOrderSkuChange()
        })
      } else {
        this.form.boxDetailIsEmpty = e
        this.refreshOrderSkuChange()
      }
    },
    changeBoxIsEmpty(e) {
      if (e == "Y") {
        this.confirmClearBox(() => {
          this.form.boxIsEmpty = e
          this.changeCustomerPallet("N")
          this.refreshOrderSkuChange()
        })
      } else {
        this.form.boxIsEmpty = e
        this.refreshOrderSkuChange()
      }
    },
    changeCustomerPallet(e) {
      this.form.isPallet = e
      this.form.isCustomerPallet = e
    },
    changeInboundType(e) {

      this.form.inboundType = e
      this.form.customsService = this.inboundTypeTRANSIT ? 'Y' : "N"
      if (!this.inboundTypeTRANSIT) {
        this.form.boxDetailIsEmpty = 'N'
        this.productChange(null)
      }
      this.changeInsurance("N")
      this.startWarehouseChange(null)
      this.form.expectedDate = null

    },
    changeInsurance(e) {
      const isInsurance = this.form.isInsurance
      // this.form.isInsurance = e
      this.$set(this.form, 'isInsurance', e)
      this.form.omsBoxSkuInfoVOList.forEach(it => {
        it.isInsurance = e
        if (e == "N") it.insuredAmount = 0
      })
      if (isInsurance != e) {
        this.refreshOrderSkuChange()
      }
    },
    changeCustomer(e) {

      if (!e) e = { customerId: null, customerName: null, customerCode: null }
      this.confirmClearBox(() => {
        this.form.customerId = e.customerId
        this.form.customerName = e.customerName
        this.form.customerCode = e.customerCode
      })
    },
    //清空sku确认
    confirmClearBox(fun) {
      if (_.isEmpty(this.form.omsBoxSkuInfoVOList)) {
        fun()
      } else {
        this.$confirm(this.$tt('tip_this_operate_will_fill_empty_sku_list'), this.$tt('label_tip'), {
          type: 'warning'
        }).then(() => {
          this.removeSkuAll()
          fun()
        }).catch(() => {
        });
      }
    },
    confirmClearBoxNo(fun) {
      if (_.isEmpty(this.form.omsBoxSkuInfoVOList)) {
        fun()
      } else {
        this.$confirm(this.$tt('tip_this_operate_will_fill_empty_box_no'), this.$tt('label_tip'), {
          type: 'warning'
        }).then(() => {

          this.form.omsBoxSkuInfoVOList.forEach(it => this.$set(it, 'boxNo', null))
          this.refreshOrderSkuChange()
          fun()
        }).catch(() => {
        });
      }
    },
    removeSkuAll() {
      this.form.omsBoxSkuInfoVOList = []
      this.refreshOrderSkuChange()
    },



    //箱号修改，带动箱子序号变动
    boxNoChange() {
      //获取唯一值数组
      const boxList = this.groupBoxList
      this.form.omsBoxSkuInfoVOList.map(it => {
        this.$set(it, 'boxNumber', _.findIndex(boxList, item => item.boxNo == it.boxNo) + 1)
      })
    },





    //刷新订单总计投保有关数据
    refreshOrderSkuChange() {
      this.form.expectBoxQty = this.expectBoxQtyCompute()
      this.form.expectSkuQty = this.expectSkuQtyCompute()
      this.form.totalWeight = this.totalWeightCompute()
      this.form.totalVolume = this.totalVolumeCompute()

      if (!this.CanInsurance) {
        this.form.omsBoxSkuInfoVOList.forEach(it => {
          this.$set(it, "isInsurance", "N")
          this.$set(it, "insuredAmount", 0)
        })
      }
      this.boxNoChange()
      // if (this.CanInsurance) {
      //   if (!_.isEmpty(this.form.omsBoxSkuInfoVOList)) {
      //     let order_isInsurance = this.form.omsBoxSkuInfoVOList.some(it => it.isInsurance == "Y")
      //     this.$set(this.form, "isInsurance", order_isInsurance ? 'Y' : "N")
      //   }
      // } else {
      //   this.$set(this.form, "isInsurance", "N")
      // }


    },



    skuNumberChange(item,) {
      // item.skuDeclaredValue = this.$math_mul(item.skuItem.skuDeclaredValue, number)
      item.skuWeight = this.$math_mul(item.skuItem.skuWeight, item.quantity)
      item.skuVolume = this.$math_mul(item.skuItem.skuVolume, item.quantity)

    },
    removeSku(index) {
      this.form.omsBoxSkuInfoVOList.splice(index, 1)
      this.refreshOrderSkuChange()
    },

    skuItemComplete(item) {

      // item.skuDeclaredAmount = this.$math_mul(item.skuItem.skuDeclaredValue, item.quantity)
      item.skuWeight = this.$math_mul(item.skuItem.skuWeight, item.quantity)
      item.skuVolume = this.$math_mul(item.skuItem.skuVolume, item.quantity)

    },

    expectSkuQtyCompute() {//总件（包）数   根据底下货物计算出来quantity
      return _.reduce(this.form.omsBoxSkuInfoVOList, (r, v) => this.$math_add(r, (v.quantity)), 0)
    },

    expectBoxQtyCompute() {//总箱数   根据底下货物计算出来
      if (this.BoxCodeManage) {
        return this.uniqBoxList.length

      } else {
        return 0
      }
    },
    totalWeightCompute() {//总重量   根据底下货物计算出来
      let sum = 0
      if (this.BoxCodeManage) {
        sum = _.reduce(this.uniqBoxList, (r, v) => this.$math_add(r, v.boxWeight), 0)
      } else {
        sum = _.reduce(this.form.omsBoxSkuInfoVOList, (r, v) => this.$math_add(r, this.$math_mul(v.quantity, v.skuWeight)), 0)
      }
      return this.$math_ceil(sum, 3, false)
    },
    totalVolumeCompute() {//总体积    根据底下货物计算出来
      let sum = 0
      if (this.BoxCodeManage) {
        sum = _.reduce(this.uniqBoxList, (last, it) => {
          const v_cm = this.$math_mul(it.boxLength, it.boxWidth, it.boxHeight)
          return this.$math_add(last, v_cm)
        }, 0)
      } else {
        sum = _.reduce(this.form.omsBoxSkuInfoVOList, (last, it) => {
          const v_cm = this.$math_mul(it.quantity, it.skuLength, it.skuWidth, it.skuHeight)
          return this.$math_add(last, v_cm)
        }, 0)
      }

      const v_m = this.$math_mul(sum, 0.000001)
      return this.$math_ceil(v_m, 8, false)
    },

    submit(opEnum) {
      if (this.$clickFast()) return
      this.$refs['form'].validate((valid, obj) => {
        if (valid) {
          this.changeInitDeliveryInfo()
          if (opEnum == 'SAVE_AUDIT') {
            const h = this.$createElement;
            const transitWarehouse = this.form.transitWarehouseId ? h('div', { class: 'flex_row' }, [`${this.$tt('label_transit_warehouse')} : ${this.$formatNameCode(this.form.transitWarehouseName, this.form.transitWarehouseCode)}`]) : null
            const product = this.form.productId ? h('div', { class: 'flex_row' }, [`${this.$tt('label_logistics')} : ${this.$formatNameCode(this.form.productName, this.form.productCode)}`]) : null
            const message = h('div', [
              h('div', { class: 'flex_row' }, [`${this.$tt('label_destination_warehouse')} : ${this.$formatNameCode(this.form.destinationWarehouseName, this.form.destinationWarehouseCode)}`]),
              transitWarehouse,
              product,
            ])
            this.$msgbox({
              title: this.$tt('label_tip'),
              showCancelButton: true,
              message: message,
            }).then(() => {
              this.submitNet(opEnum)
            }).catch(() => {
            });
          } else {
            this.submitNet(opEnum)
          }
        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });
    },
    submitNet(opEnum) {

      let data = _.cloneDeep(this.form)

      if (!this.deliveryTypeCOLLECT) {
        delete data.omsInboundReceivingAddressDTO
      }
      data.omsBoxSkuInfoVOList.map(it => {
        delete it.skuItem
      })


      data.opEnum = opEnum

      data.platformCode = ""
      data.platformName = ""
      data.appId = ""

      // data.expectSkuQty = this.expectSkuQtyCompute
      // data.totalWeight = this.totalWeightCompute
      // data.expectBoxQty = this.expectBoxQtyCompute
      // data.totalVolume = this.totalVolumeCompute

      data.insuranceValue = this.insuredAmountSum
      data.isPallet = data.isCustomerPallet

      this.$ajax({
        url: data.id ? this.$url['oms/inboundOrderUpdate'] : this.$url['oms/inboundOrderSave'],
        type: 'json',
        method: 'post',
        data,
        loading: true,
        success: (res) => {
          this.$message.success(this.$tt('tip_submit_success'))
          this.return_emit(null, "reload")
          this.$tag.tagClose(null, this.intoPath)
        },

      })
    },
    startWarehouseChange(e) {
      if (e) {
        this.form.transitWarehouseId = e.warehouseId
        this.form.transitWarehouseCode = e.warehouseCode
        this.form.transitWarehouseName = e.warehouseName
      } else {
        this.form.transitWarehouseId = null
        this.form.transitWarehouseCode = null
        this.form.transitWarehouseName = null
      }
      this.productChange(null)
    },
    refreshEndWarehouseLink() {
      if (this.form.destinationWarehouseId) {
        const wh = this.$store.state.allWarehouseMap[this.form.destinationWarehouseId]
        if (wh) {
          this.hiddenValueAddService = wh.position == "DOMESTIC"
          this.form.customsService = 'N'
          this.form.customsType = 'NO_TAX'
          this.form.isWarehouseReceiptPrevail = 'Y'
          this.changeInsurance("N")
        } else {
          this.hiddenValueAddService = false
        }
      } else {
        this.hiddenValueAddService = false
      }
    },
    endWarehouseChange(e) {
      if (e) {
        this.form.destinationWarehouseId = e.warehouseId || e.id
        this.form.destinationWarehouseCode = e.warehouseCode || e.code
        this.form.destinationWarehouseName = e.warehouseName || e.name
      } else {
        this.form.destinationWarehouseId = null
        this.form.destinationWarehouseCode = null
        this.form.destinationWarehouseName = null
      }
      this.refreshEndWarehouseLink()


      this.startWarehouseChange(null)
    },
    productChange(e) {
      if (this.$loginUser.ifElse英威特) {
        e = _.head(this.ProductList)
        this.form.customsType = "NO_TAX"
      }
      if (e) {
        this.form.productId = e.productId
        this.form.productName = e.productName
        this.form.productCode = e.productCode

      } else {
        this.form.productId = null
        this.form.productName = null
        this.form.productCode = null
      }

      this.changeInsurance("N")

    },
    initProduct() {

      this.loading = true
      this.$ajax({
        url: this.$url['fms/getFirstProduct'],
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          if (res && res.data && res.data.rows) {
            this.products = res.data.rows

          }
        },
      })
    },

    uploadSkuFile(cfg) {
      if (!this.form.customerId) return this.$message.warning(this.$tt("tip_please_select_first_customer"))
      this.confirmClearBox(() => {
        this.$uploadFile({
          loading: true,
          url: this.$url['oms/inboundOrderImportSku'],
          file: cfg.file,
          headers: {
            customerCode: this.form.customerCode
          },
          success: (res) => {
            if (res && res.data && res.data.rows) {
              this.removeSkuAll()
              this.form.omsBoxSkuInfoVOList.push(...res.data.rows)
              this.refreshOrderSkuChange()
            }
          },
        })
      })

    },
  }
};

</script>
<style scoped></style>
